/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CP2013Server;

import cp2013.Item;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Queue;
import java.util.regex.Pattern;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author AcerXPS
 */
public class ManageUI extends JFrame {

    private ManageUI frame = this;
    private AuctionDatabase dB;
    private Queue dataQ;
    private JPanel managePanel;
    private int rowNum;
    private int colNum;
    private JTable manageTable;
    private TableModel tableModel;
    private DefaultTableColumnModel columnModel;
    private JScrollPane manageScroll;
    private JButton btnRefresh;
    private JButton btnEdit;
    private JButton btnDelete;
    private JButton btnClose;
    private ButtonListener listener;
    private String[][] data;
    private final String[] colNames = {"ID", "Item Name", "Starting Bid", "Seller Name", "Start Date", "Finish Date", "Highest Bidder", "Description", "Seller ID", "Current Bid", "Status"};
    private final Insets buttonInsets = new Insets(2, 8, 2, 8);

    public ManageUI(AuctionDatabase dB) {
        super("Manage Auction Objects");
        this.dB = dB;
    }

    public void initiateUI() {
        this.managePanel = new JPanel();
        managePanel.setLayout(new BorderLayout());
        this.initiateTable();
        JPanel buttonPanel = new JPanel();
        this.btnRefresh = new JButton("Refresh Table");
        this.btnRefresh.setMargin(buttonInsets);
        this.btnEdit = new JButton("Edit Selected Cell");
        this.btnEdit.setMargin(buttonInsets);
        this.btnDelete = new JButton("Delete Selected Item");
        this.btnDelete.setMargin(buttonInsets);
        this.btnClose = new JButton("Close Window");
        this.btnClose.setMargin(buttonInsets);
        listener = new ButtonListener();
        this.addListener(listener);
        buttonPanel.add(this.btnRefresh);
        buttonPanel.add(this.btnEdit);
        buttonPanel.add(this.btnDelete);
        buttonPanel.add(this.btnClose);
        buttonPanel.setLayout(new FlowLayout());
        this.managePanel.add(buttonPanel);
        this.getContentPane().add(managePanel);
    }

    private void initiateTable() {
        dataQ = dB.manageQuery();
        this.rowNum = dataQ.size();
        this.colNum = 11;
        this.data = new String[rowNum][colNum];
        for (int i = 0; i < rowNum; i++) {
            Item item = (Item) dataQ.poll();
            data[i][0] = String.valueOf(item.getItemId());
            data[i][1] = item.getItemName();
            data[i][2] = String.valueOf(item.getStartingBid());
            data[i][3] = item.getSellerName();
            data[i][4] = item.getStartDate();
            data[i][5] = item.getFinishDate();
            data[i][6] = item.getHighestBidder();
            data[i][7] = item.getDescription();
            data[i][8] = String.valueOf(item.getSellerID());
            data[i][9] = String.valueOf(item.getCurrentBid());
            data[i][10] = item.getStatus();
        }

        this.tableModel = new TableModel(data, colNames);
        this.columnModel = new ColumnModel();
        this.manageTable = new JTable(tableModel, columnModel);
        manageTable.createDefaultColumnsFromModel();
        manageTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        this.adjustColSize(0, 40);
        this.adjustColSize(1, 120);
        this.adjustColSize(3, 80);
        this.adjustColSize(7, 240);
        this.adjustColSize(6, 100);
        this.manageScroll = new JScrollPane(manageTable);
        this.managePanel.add(BorderLayout.NORTH, manageScroll);
    }

    private void adjustColSize(int vColIndex, int width) {
        TableColumn col = manageTable.getColumnModel().getColumn(vColIndex);
        col.setPreferredWidth(width);
    }

    public JPanel getPanel() {
        return managePanel;
    }

    private void refreshTable() {
        managePanel.remove(manageScroll);
        frame.initiateTable();
        managePanel.validate();
        frame.repaint();
    }

    public void addListener(ActionListener listener) {
        btnRefresh.addActionListener(listener);
        btnEdit.addActionListener(listener);
        btnDelete.addActionListener(listener);
        btnClose.addActionListener(listener);
    }

    private class ButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == btnRefresh) {
                frame.refreshTable();
            } else if (e.getSource() == btnEdit) {
                String queryColName;
                String expression = "^(18|19|20|21)\\d{2}[- / ]?(0[1-9]|1[012]|[1-9])[- /]?(0[1-9]|[1-9]|[12][0-9]|3[01])$";
                String dateEx = "YYYY/MM/DD";
                String newValue = null;
                int selectedRow = manageTable.getSelectedRow();
                int selectedCol = manageTable.getSelectedColumn();
                int selectedID = Integer.parseInt(data[selectedRow][0]);
                boolean editStatus = false;

                if (selectedCol == 0 || selectedCol == 3 || selectedCol == 8) {
                    JOptionPane.showMessageDialog(rootPane, "You are not allowed to edit this property");
                } else {
                    String selectedProperty = colNames[selectedCol];
                    if (selectedProperty.equalsIgnoreCase("finish date") || selectedProperty.equalsIgnoreCase("start date")) {
                        newValue = JOptionPane.showInputDialog(rootPane, "Updating Item ID: " + selectedID + ", please enter new value for item's " + selectedProperty + " ("+dateEx+"):", "Editing Item", JOptionPane.QUESTION_MESSAGE);
                    } else {
                        newValue = JOptionPane.showInputDialog(rootPane, "Updating Item ID: " + selectedID + ", please enter new value for item's " + selectedProperty + ":", "Editing Item", JOptionPane.QUESTION_MESSAGE);
                    }
                    
                    if (newValue != null) {
                        switch (selectedCol) {
                            case 1:
                                queryColName = "Name";
                                editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                break;
                            case 2:
                                queryColName = "Starting_bid";
                                try {
                                    Integer.parseInt(newValue);
                                    editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                } catch (Exception ex) {
                                    JOptionPane.showMessageDialog(rootPane, "Starting bid must be a number");
                                }
                                break;
                            case 4:
                                queryColName = "Start_date";
                                if (!Pattern.matches(expression, newValue)) {
                                    JOptionPane.showMessageDialog(rootPane, "Date must be in YYYY/MM/DD format");
                                } else {
                                    editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                    // update item
                                }
                                break;
                            case 5:
                                queryColName = "Finish_date";
                                if (!Pattern.matches(expression, newValue)) {
                                    JOptionPane.showMessageDialog(rootPane, "Date must be in YYYY/MM/DD format");
                                } else {
                                    editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                    // update item
                                }
                                break;
                            case 6:
                                queryColName = "Highest_bidder";
                                editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                break;
                            case 7:
                                queryColName = "Description";
                                editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                break;
                            case 9:
                                queryColName = "Current_bid";
                                try {
                                    Integer.parseInt(newValue);
                                    editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                } catch (Exception ex) {
                                    JOptionPane.showMessageDialog(rootPane, "Current bid must be a number");
                                }
                                break;
                            case 10:
                                queryColName = "Status";
                                if (newValue.equalsIgnoreCase("active") || newValue.equalsIgnoreCase("inactive")) {
                                    editStatus = dB.updateQuery(queryColName, selectedID, newValue);
                                } else {
                                    JOptionPane.showMessageDialog(rootPane, "Input must be either \"ACTIVE\" or \"INACTIVE\"");
                                }
                        }
                        if (editStatus == true) {
                            JOptionPane.showMessageDialog(rootPane, "Success editing item ID: " + selectedID);
                            frame.refreshTable();
                        } else {
                            JOptionPane.showMessageDialog(rootPane, "Error Occured, please try again later");
                        }
                    }
                }
            } else if (e.getSource() == btnDelete) {
                int selectedRow = manageTable.getSelectedRow();
                String selectedID = data[selectedRow][0];
                int option = JOptionPane.showConfirmDialog(rootPane, "Are you sure want to delete item with ID: " + selectedID + " ?", "Deleting Item", JOptionPane.YES_NO_OPTION);
                if (option == JOptionPane.YES_OPTION) {
                    boolean status = dB.deleteQuery(Integer.parseInt(selectedID));
                    if (status == true) {
                        JOptionPane.showMessageDialog(rootPane, "Success deleting item ID: " + selectedID);
                        frame.refreshTable();
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "Error deleting item, please try again");
                    }
                }


            } else if (e.getSource() == btnClose) {
                frame.dispose();
            }
        }
    }

    private class TableModel extends DefaultTableModel {

        public TableModel(String[][] data, String[] col) {
            super(data, col);
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    }

    private class ColumnModel extends DefaultTableColumnModel {

        public ColumnModel() {
            super();
        }

        @Override
        public void moveColumn(int colIndex, int newIndex) {
            //do nothing
        }
    }
}
